package com.gcloud.mesh.dcs.task;

import com.gcloud.mesh.dcs.dao.AppDao;
import com.gcloud.mesh.dcs.dao.SchedulerImagineDao;
import com.gcloud.mesh.dcs.dao.SchedulerJobDao;
import com.gcloud.mesh.dcs.entity.SchedulerImagineEntity;
import com.gcloud.mesh.dcs.entity.SchedulerJobEntity;
import com.gcloud.mesh.dcs.enums.SchedulerJobStatus;
import com.gcloud.mesh.dcs.enums.SchedulerModelDict;
import com.gcloud.mesh.dcs.service.ModelService;
import com.gcloud.mesh.dcs.service.SchedulerService;
import com.gcloud.mesh.header.enums.ModelType;
import com.gcloud.mesh.header.msg.dcs.GetModelFactorsMsg;
import com.gcloud.mesh.header.vo.dcs.ModelFactorVo;
import com.gcloud.mesh.monitor.service.StatisticsCheatService;
import com.gcloud.mesh.supplier.dao.SupplierDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Slf4j
@Component
public class SchedulerTask {

	@Autowired
	private SchedulerService schedulerService;

	@Autowired
	private SchedulerJobDao schedulerJobDao;

	@Autowired
	private SupplierDao supplierDao;
	
	@Autowired
	private ModelService modelService;

	@Autowired
	private AppDao appDao;

	@Autowired
	private SchedulerImagineDao schedulerImagineDao;

	@Autowired
	private StatisticsCheatService statisticsCheatService;

	private StringBuilder scores;

	@Scheduled(fixedDelay = 1000 * 10)
	public void work() {
		log.debug("[Scheduler] 调度定时器开始");

		List<SchedulerJobEntity> jobs = schedulerJobDao.findByProperty("status", SchedulerJobStatus.READY.getValue());
		if (jobs != null) {
			for (SchedulerJobEntity job : jobs) {

				// AppEntity appEntity = appDao.getById(job.getAppId());
				//
				//
				// if(appEntity==null) continue;
				//
				// SupplierEntity supplierEntity =
				// supplierDao.findOneByProperty("datacenterId",
				// job.getSrcDatacenterId());
				//
				// if(supplierEntity==null) continue;

				try {
					job.setBeginTime(new Date());
					updateSchedulerImagine(job);
					schedulerJobDao.updateJobStatus(job, SchedulerJobStatus.PROGRESS);
					schedulerService.updateSchedulerJob(job);
					schedulerService.schedule(job);
					
					// k8s
					// if(SystemType.K8S.getName().equalsIgnoreCase(supplierEntity.getType()))
					// {
					// schedulerJobDao.updateJobStatus(job,
					// SchedulerJobStatus.SUCCESS);
					// }
				} catch (Exception e) {
					schedulerJobDao.updateJobStatus(job, SchedulerJobStatus.FAIL);
					log.error("[Scheduler]调度错误", e);
				}

			}
		}

		log.debug("[Scheduler] 调度定时器结束");
	}

	private void updateSchedulerImagine(SchedulerJobEntity job) {
		ModelType modelType = ModelType.get(SchedulerModelDict.get(String.valueOf(job.getSchedulerModel())).name());
		SchedulerImagineEntity entity = schedulerImagineDao.get(modelType, job.getAppId(), job.getSrcDatacenterId(), job.getDstDatacenterId(),
				SchedulerImagineEntity.class);
		
		GetModelFactorsMsg fm = new GetModelFactorsMsg();
		fm.setModelType(modelType.name());
		List<ModelFactorVo> factors = modelService.getModelFactors(fm);
		
		StringBuilder imagines = new StringBuilder();
		StringBuilder factorTypes = new StringBuilder();
		for(ModelFactorVo factor : factors){
			if(factor.getEnabled()){
				
				String valueStr = statisticsCheatService.latestSample(factor.getFactorType(), job.getSrcDatacenterId());
				Double value = Double.parseDouble(valueStr);
				BigDecimal valueb = new BigDecimal(value);
				value = valueb.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
				
				if (imagines.length() > 0) {
					imagines.append(",");
				}
				if (factorTypes.length() > 0) {
					factorTypes.append(",");
				}
				imagines.append(value);
				factorTypes.append(factor.getFactorType());
			}
		}

		
		if (entity != null) {
			// schedulerImagineDao.updateAfter(entity, temperature,
			// distributionBoxVoltage, datacenterEnergy,businessRespond);
			schedulerImagineDao.delete(entity);
		}
		
		SchedulerImagineEntity schedulerImagineEntity = new SchedulerImagineEntity();
		schedulerImagineEntity.setId(UUID.randomUUID().toString());
		schedulerImagineEntity.setAppId(job.getAppId());
		schedulerImagineEntity.setSourceNodeId(job.getSrcDatacenterId());
		schedulerImagineEntity.setDestNodeId(job.getDstDatacenterId());
		schedulerImagineEntity.setModelType(modelType.name());
		schedulerImagineEntity.setImagines(imagines.toString());
		schedulerImagineEntity.setFactorTypes(factorTypes.toString());
		schedulerImagineDao.save(schedulerImagineEntity);
	}

}
